package com.ebt.m.customer.ui;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.GetObjectRequest;
import com.alibaba.sdk.android.oss.model.GetObjectResult;
import com.ebt.m.R;
import com.ebt.m.activity.BaseToolBarActivity;
import com.ebt.m.commons.utils.NetUtils;
import com.ebt.m.commons.utils.ToastUtil;
import com.ebt.m.customer.CustomerUtil;
import com.ebt.m.customer.constant.CustomerConstant;
import com.ebt.m.customer.event.EventRefreshAttachment;
import com.ebt.m.customer.net.http.OSSUploader;
import com.ebt.m.customer.util.AttachmentUtil;
import com.ebt.m.data.bean.EbtFile;
import com.ebt.m.data.entity.EntityCustomerAttachment;
import com.ebt.m.repository.provider.FileTypeHelper;
import com.ebt.m.repository.provider.RepositoryProvider;
import com.ebt.m.utils.UIHelper;
import com.ebt.m.utils.fileutils.FileUtils;
import com.ebt.m.widget.MDEBTDialog;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Damon on 2017/12/1.
 * 文件下载
 */

public class ActivityAttachmentDoload extends BaseToolBarActivity {

    @BindView(R.id.thumb)
    ImageView thumb;
    @BindView(R.id.file_name)
    TextView fileName;
    @BindView(R.id.file_size)
    TextView fileSize;
    @BindView(R.id.preview_or_not)
    TextView previewOrNot;
    @BindView(R.id.progress_txt)
    TextView progressTxt;
    @BindView(R.id.progress)
    ProgressBar progress;
    @BindView(R.id.download_area)
    View downloadingArea;
    @BindView(R.id.img_cancel)
    ImageView imgCancel;
    @BindView(R.id.to_download)
    TextView toDownload;
    @BindView(R.id.to_open)
    TextView toOpen;
    private Context mContext;
    private EntityCustomerAttachment customerAttachment;
    private EbtFile mFile;
    private long fileSizeTotal;
    private OSSAsyncTask ossAsyncTask;

    public static final int DOWNLOAD_STATE_READY = 100;
    public static final int DOWNLOAD_STATE_DOWNLOADING = 200;
    public static final int DOWNLOAD_STATE_SUCCESS = 300;
    public static final int DOWNLOAD_STATE_FAIL = 400;


    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            switch (message.what) {
                case DOWNLOAD_STATE_READY:
                    progress.setProgress(0);
                    downloadingArea.setVisibility(View.GONE);
                    toDownload.setVisibility(View.VISIBLE);
                    break;
                case DOWNLOAD_STATE_DOWNLOADING:
                    toDownload.setVisibility(View.GONE);
                    downloadingArea.setVisibility(View.VISIBLE);
                    progress.setProgress(0);
                    break;
                case DOWNLOAD_STATE_SUCCESS:
                    downloadingArea.setVisibility(View.GONE);
                    toDownload.setVisibility(View.GONE);
                    toOpen.setVisibility(View.VISIBLE);
                    //显示文件大小
                    String fileSizeStr = FileUtils.formatFileSize(fileSizeTotal);
                    fileSize.setText(fileSizeStr);
                    ToastUtil.show(mContext, "附件下载成功");
                    break;
                case DOWNLOAD_STATE_FAIL:
                    ToastUtil.show(mContext, "附件下载失败");
                    break;
            }

            return false;
        }
    });

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.customer_activity_attachment_doload);
        ButterKnife.bind(this);
    }

    @Override
    public void init() {
        Bundle bundle = getIntent().getExtras();
        customerAttachment = (EntityCustomerAttachment) bundle.getSerializable("data");
        if (customerAttachment == null) {
            finish();
        }
        //TODO文件大小
//        customerAttachment.get
        fileName.setText(customerAttachment.fileName);
        mFile = CustomerUtil.convertAttachmentToEbtFile(customerAttachment);
        new RepositoryProvider(mContext).setThumbnailImage(thumb, mFile);
        fileSize.setText(customerAttachment.content);

    }


    @OnClick(R.id.thumb)
    public void onThumbClicked() {
        toOpen();
    }

    @OnClick(R.id.img_cancel)
    public void onImgCancelClicked() {
        if (ossAsyncTask != null && !ossAsyncTask.isCompleted()) {
            ossAsyncTask.cancel();
        }
        Message message = handler.obtainMessage();
        message.what = DOWNLOAD_STATE_READY;
        handler.sendMessage(message);
    }

    @OnClick(R.id.to_download)
    public void onToDownloadClicked() {
        downloadAtta();
    }

    @OnClick(R.id.to_open)
    public void onToOpenClicked() {
        toOpen();
    }

    //打开已下载的文件
    private void toOpen() {
        File f = new File(AttachmentUtil.netPathToLocalPath(customerAttachment.path, CustomerConstant.Attachment.DIR_PATH + File.separator));
        if (f.exists()) {
            openFile(f);
        }
    }

    private void openFile(File file) {
        if (!file.exists()) {
            Toast.makeText(mContext, "文件不存在，请先下载", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            FileUtils.openFile(mContext, file);
        } catch (Exception e) {
            UIHelper.makeToast(mContext,"无法打开此文件格式");
            e.printStackTrace();
        }
    }



    private void downloadAtta() {
        Log.d("wang", "atta.path : " + customerAttachment.path);
        if (AttachmentUtil.isPathFromNet(customerAttachment.path)) {
            //下载文件
            Message message = handler.obtainMessage();
            message.what = DOWNLOAD_STATE_DOWNLOADING;
            handler.sendMessage(message);
            String[] paths = customerAttachment.path.split("/");
            if (paths != null && paths.length > 0) {
                String subFileName = paths[paths.length - 1];
                ossAsyncTask = OSSUploader.downloadAttachment(AttachmentUtil.urlDecode(subFileName), new OnOSSDownloadResponseListener(customerAttachment.path));
            }
        } else {
            Toast.makeText(mContext, "附件不存在", Toast.LENGTH_SHORT).show();
        }
    }

    private class OnOSSDownloadResponseListener implements OSSCompletedCallback<GetObjectRequest, GetObjectResult> {

        private String netPath;

        public OnOSSDownloadResponseListener(String netPath) {
            this.netPath = netPath;
        }

        @Override
        public void onSuccess(GetObjectRequest getObjectRequest, GetObjectResult getObjectResult) {
            fileSizeTotal = getObjectResult.getContentLength();
            if (fileSizeTotal < CustomerConstant.Attachment.SIZE_1_M) {
                //直接下载
                saveInputStream(getObjectResult.getObjectContent(), netPath);
            } else {
                //如果是在wifi下，直接下载
                if (NetUtils.isWifiConnected(mContext)) {
                    saveInputStream(getObjectResult.getObjectContent(), netPath);
                } else {
                    //移动网络下，确认是否下载
                    popupWantDownloadDialog(getObjectResult.getObjectContent(), netPath);
                }
            }
        }

        @Override
        public void onFailure(GetObjectRequest getObjectRequest, ClientException e, ServiceException e1) {
            com.ebt.m.commons.utils.ToastUtil.show(mContext, "附件下载失败");
            Message message = handler.obtainMessage();
            message.what = DOWNLOAD_STATE_READY;
            handler.sendMessage(message);
            // 请求异常
            if (e != null) {
                // 本地异常如网络异常等
                e.printStackTrace();
            }
            if (e1 != null) {
                // 服务异常
                Log.e("ErrorCode", e1.getErrorCode());
                Log.e("RequestId", e1.getRequestId());
                Log.e("HostId", e1.getHostId());
                Log.e("RawMessage", e1.getRawMessage());
            }
        }
    }

    private void popupWantDownloadDialog(final InputStream inputStream, final String netPath) {
        String[] messages = new String[]{"当前非移动网络，确定下载附件？"};
        new MDEBTDialog.Builder(this.mContext)
                .setMessages(messages)
                .setTitle("下载提醒")
                .setShowButtons(true)
                .setContentViewClickable(false)
                .setPositiveButton(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Message message = handler.obtainMessage();
                        message.what = DOWNLOAD_STATE_DOWNLOADING;
                        handler.sendMessage(message);
                        saveInputStream(inputStream, netPath);
                    }
                })
                .setNegativeButton(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                    }
                })
                .create()
                .show();

    }

    private void saveInputStream(InputStream inputStream, String netPath) {
        boolean result = false;
        String localPath = AttachmentUtil.netPathToLocalPathWithoutCareExist(netPath, CustomerConstant.Attachment.DIR_PATH + File.separator);
        File targetFile = new File(localPath);
        if (targetFile.exists()) {
            targetFile.delete();
        }
        try {
            targetFile.createNewFile();
            OutputStream os = new FileOutputStream(targetFile);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            long size = 0;
            while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
                size += buffer.length;
                int progressInt = (int) (size / fileSizeTotal) * 100;
                progress.setProgress(progressInt);
//                progressTxt.setText(progressInt+"%");
            }
            os.close();
            inputStream.close();
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
            targetFile.delete();
        }
        if (mFile.type == FileTypeHelper.FileTypeAll.FILE_TYPE_IMAGE) {
            FileUtils.scanImageFile(mContext, targetFile);
        }
        if (result) {
            Message message = handler.obtainMessage();
            message.what = DOWNLOAD_STATE_SUCCESS;
            handler.sendMessage(message);
            EventBus.getDefault().post(new EventRefreshAttachment(true));
        } else {
            Message message = handler.obtainMessage();
            message.what = DOWNLOAD_STATE_FAIL;
            handler.sendMessage(message);
        }
    }

}
